package immoc_collection.map.demo;

import java.util.*;

public class MapTest {

    public Map<String, Student> students;

    public MapTest() {
        this.students = new HashMap<String, Student>();
    }

    /**
     * 输入学生ID, 判断是否存在
     * 不存在就创建学生, 并且添加到students
     */
    public void testPut() {
        Scanner scanner = new Scanner(System.in);
        int i = 0;
        while (i < 3) {
            System.out.println("请输入学生ID:");
            String id = scanner.next();
            Student st = this.students.get(id);
            if (st == null) {
                // 输入学生的ID和姓名
                System.out.println("请输入学生的姓名:");
                String name = scanner.next();
                this.students.put(id, new Student(id, name));
                System.out.println("成功添加学生: " + students.get(id).name);
                i ++;
            } else {
                System.out.println(id + "已存在!");
            }
        }
    }

    public void testKeySet() {
        System.out.println("总共有学生: " + this.students.size() + "个学生");
        // 获取所有键的集合
        Set<String> keySet = students.keySet();
        for (String key: keySet) {
            Student st = this.students.get(key);
            if (st != null) {
                System.out.println("学生: " + key + " : " +st.name);
            }
        }
    }

    public void testEntrySet() {
        // 返回所有键值对的集合
        System.out.println("通过entrySet获取值");
        Set<Map.Entry<String, Student>> entrySet = students.entrySet();
        for (Map.Entry<String, Student> entry: entrySet) {
            System.out.println("取得键" + entry.getKey());
            System.out.println("取得值" + entry.getValue().name);
        }
    }

    public void testRemove() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("输入需要删除的学生ID:");
            String id = scanner.next();
            Student st = this.students.get(id);
            if (st != null) {
                students.remove(id);
                System.out.println("删除学生: " + id + " : " +st.name);
                break;
            } else {
                System.out.println("不存在此元素");
            }
        }

    }

    public void testEdit() {
        // 相同键, 值覆盖?
        students.put("1", new Student("1", "替换后的学生"));
    }

    public static void main(String[] args) {
        MapTest mt = new MapTest();
        mt.testPut();
        mt.testKeySet();
//        mt.testKeySet(); // 好像不是无序??

        /*mt.testRemove();
        mt.testEntrySet();*/

        mt.testEdit();
        mt.testKeySet();

    }
}
